<template>
  <div>
    <div class="login-box">
      <h2>中心登录</h2>
      <el-form :model="loginInfo" label-width="70px" ref="loginForm"
               :show-message="false">
        <el-form-item prop="username" label="用户名" required>
          <el-input v-model="loginInfo.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" required>
          <el-input v-model="loginInfo.password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item prop="code" label="验证码" required>
          <el-input placeholder="输入验证码" v-model="loginInfo.code">
            <template slot="append">
              <span class="valid-code" @click="flashValid" v-text="validCode"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doLogin">登 录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  export default {
    name: "Login",
    data() {
      return {
        loginInfo: {
          username: '',
          password: '',
          code: ''
        },
        rules: {
        },
        validCode: 0,
        time: 0,
        timeout: null
      }
    },
    methods: {
      doLogin() {
        this.$refs['loginForm'].validate(valid => {
          if (valid) {
            this.$axios.post('/user/login', this.$utils.toFd(this.loginInfo)).then(rs => {
              let token = rs.data.payload
              this.$utils.setToken(token)
              this.$message({
                message: "登录成功！",
                type: 'success',
                duration: 1200
              })
              setTimeout(() => {
                this.$router.push("/admin")
              }, 1000)
            }).catch(err => {
              this.$message.error("登录失败：" + err.msg)
            })
          }
        })
      },
      /**
       * 刷新验证码
       */
      flashValid() {
        if (this.timeout == null) {
          this.timeout = setTimeout(v => {
            clearTimeout(this.timeout)
            this.time = 0
            this.timeout = null
          }, 30 * 1000)
        }
        if (++this.time < 5) {
          this.$axios.get('/user/verify').then(rs => {
            this.validCode = rs.data.payload
          }).catch(err => {
            this.validCode = 'err'
          })
        } else {
          this.$message.warning('验证码刷新过于频繁！')
        }
      }
    },
    created() {
      this.flashValid()
    }
  }
</script>

<style scoped>
  .login-box {
    max-width: 420px;
    margin: 0 auto
  }

  .login-box h2 {
    text-align: center;
    margin-top: 20vh;
    margin-bottom: 20px;
  }

  .valid-code {
    display: inline-block;
    cursor: pointer;
    width: 42px;
    text-align: center;
  }
</style>